import React, { useState } from 'react';
import './FormationControl.css';

const FormationControl = ({
  formationController,
  formationState,
  isVisible = true
}) => {
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);

  if (!isVisible || !formationController || !formationState) return null;

  const handleFormationToggle = () => {
    formationController.toggleFormation();
  };

  const handleFormationTypeChange = (type) => {
    formationController.setFormationType(type);
  };

  const handleRadiusChange = (radius) => {
    formationController.setFormationRadius(parseFloat(radius));
  };

  const handleHeightChange = (height) => {
    formationController.setFormationHeight(parseFloat(height));
  };

  const handleProgramActivate = (programName) => {
    if (formationState.activeProgram === programName) {
      formationController.activateProgram(null); // Deactivate
    } else {
      formationController.activateProgram(programName);
    }
  };

  const handleDroneCountChange = (count) => {
    formationController.initializeFormation(parseInt(count));
  };

  const handleRotationSpeedChange = (speed) => {
    formationController.rotationSpeed = parseFloat(speed);
  };

  const formationTypes = [
    { id: 'circle', name: 'Circle', icon: '⭕' },
    { id: 'line', name: 'Line', icon: '➖' },
    { id: 'triangle', name: 'Triangle', icon: '🔺' },
    { id: 'diamond', name: 'Diamond', icon: '💎' }
  ];

  return (
    <div className={`formation-control ${isCollapsed ? 'collapsed' : ''}`}>
      <div className="formation-header" onClick={() => setIsCollapsed(!isCollapsed)}>
        <h2>🚁 Formation Control</h2>
        <div className="header-controls">
          <div className={`formation-status ${formationState.isFormationActive ? 'active' : 'inactive'}`}>
            {formationState.isFormationActive ? '✅ ACTIVE' : '⏸️ INACTIVE'}
          </div>
          <span className={`collapse-arrow ${isCollapsed ? 'collapsed' : ''}`}>▼</span>
        </div>
      </div>

      {!isCollapsed && (
        <div className="formation-content">

      {/* Formation Toggle */}
      <div className="formation-section">
        <button
          className={`formation-toggle ${formationState.isFormationActive ? 'active' : ''}`}
          onClick={handleFormationToggle}
        >
          {formationState.isFormationActive ? '⏹️ Deactivate Formation' : '▶️ Activate Formation'}
        </button>
      </div>

      {/* Program Functions */}
      <div className="formation-section">
        <h3>🎭 Program Functions</h3>
        <div className="program-buttons">
          {Object.entries(formationState.programs).map(([key, program]) => (
            <div key={key} className="program-item">
              <button
                className={`program-btn ${formationState.activeProgram === key ? 'active' : ''}`}
                onClick={() => handleProgramActivate(key)}
                disabled={!formationState.isFormationActive && !program.active}
              >
                {key === 'orbit' ? '🌀' : '🌪️'} {program.name}
              </button>
              <p className="program-description">{program.description}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Formation Types */}
      <div className="formation-section">
        <h3>📐 Formation Patterns</h3>
        <div className="formation-types">
          {formationTypes.map(type => (
            <button
              key={type.id}
              className={`formation-type-btn ${formationState.formationType === type.id ? 'active' : ''}`}
              onClick={() => handleFormationTypeChange(type.id)}
              disabled={formationState.activeProgram !== null}
            >
              <span className="formation-icon">{type.icon}</span>
              <span className="formation-name">{type.name}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Formation Parameters */}
      <div className="formation-section">
        <h3>⚙️ Parameters</h3>
        <div className="parameter-controls">
          <div className="parameter-item">
            <label>Formation Radius:</label>
            <input
              type="range"
              min="1"
              max="8"
              step="0.5"
              value={formationState.formationRadius}
              onChange={(e) => handleRadiusChange(e.target.value)}
              disabled={formationState.activeProgram !== null}
            />
            <span>{formationState.formationRadius.toFixed(1)}m</span>
          </div>

          <div className="parameter-item">
            <label>Height Offset:</label>
            <input
              type="range"
              min="-2"
              max="2"
              step="0.2"
              value={formationState.formationHeight}
              onChange={(e) => handleHeightChange(e.target.value)}
              disabled={formationState.activeProgram !== null}
            />
            <span>{formationState.formationHeight.toFixed(1)}m</span>
          </div>

          <div className="parameter-item">
            <label>Drone Count:</label>
            <input
              type="range"
              min="2"
              max="8"
              step="1"
              value={formationState.formationDrones.length}
              onChange={(e) => handleDroneCountChange(e.target.value)}
              disabled={formationState.isFormationActive}
            />
            <span>{formationState.formationDrones.length}</span>
          </div>

          {showAdvanced && (
            <div className="parameter-item">
              <label>Rotation Speed:</label>
              <input
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={formationState.rotationSpeed}
                onChange={(e) => handleRotationSpeedChange(e.target.value)}
              />
              <span>{formationState.rotationSpeed.toFixed(1)}</span>
            </div>
          )}
        </div>
      </div>

      {/* Formation Status */}
      <div className="formation-section">
        <h3>📊 Formation Status</h3>
        <div className="status-grid">
          <div className="status-item">
            <span className="status-label">Active Drones:</span>
            <span className="status-value">{formationState.formationDrones.length}</span>
          </div>

          <div className="status-item">
            <span className="status-label">Formation:</span>
            <span className="status-value">{formationState.formationType}</span>
          </div>

          <div className="status-item">
            <span className="status-label">Program:</span>
            <span className="status-value">
              {formationState.activeProgram || 'Standard'}
            </span>
          </div>

          <div className="status-item">
            <span className="status-label">Radius:</span>
            <span className="status-value">{formationState.formationRadius.toFixed(1)}m</span>
          </div>
        </div>
      </div>

      {/* Advanced Controls Toggle */}
      <div className="formation-section">
        <button
          className="advanced-toggle"
          onClick={() => setShowAdvanced(!showAdvanced)}
        >
          {showAdvanced ? '🔼 Hide Advanced' : '🔽 Show Advanced'}
        </button>
      </div>

      {/* Instructions */}
      <div className="formation-section">
        <h3>📖 Instructions</h3>
        <div className="instructions">
          <ul>
            <li><strong>Activate Formation:</strong> Enable drone formation around main drone</li>
            <li><strong>Program Functions:</strong> Special choreographed movements</li>
            <li><strong>Orbital Dance:</strong> Drones orbit with height variations</li>
            <li><strong>Spiral Ascent:</strong> Drones spiral up and down dynamically</li>
            <li><strong>Formation Patterns:</strong> Choose geometric arrangements</li>
            <li><strong>Parameters:</strong> Adjust size, height, and drone count</li>
          </ul>
        </div>
      </div>
        </div>
      )}
    </div>
  );
};

export default FormationControl;
